/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ITask, Logger, ImportRewriteServiceImpl, ConfigManager, CodeGenerationEngine } from '../../core';
import { BuildProfileUpdaterImpl } from '../../core/import-rewrite/services/BuildProfileUpdater';
import { ITargetContext } from '../interfaces/ITargetContext';
import {TaskConstants} from '../constants/TaskConstants';
import SerializationPathUtil from '../../core/utils/SerializationPathUtil';

export abstract class BaseTask implements ITask {
  abstract readonly taskName: string;
  abstract readonly dependencies: string[];
  abstract readonly postDependencies: string[];

  protected readonly engine = new CodeGenerationEngine();
  protected readonly buildProfileUpdater = new BuildProfileUpdaterImpl();

  protected getScanFiles(context: ITargetContext): string[] {
    const scanFiles = context.getCurrentTargetScanFiles();

    if (!scanFiles || scanFiles.length === 0) {
      Logger.debug('There are no source files to be processed');
      return [];
    }

    return scanFiles;
  }

  protected processWithLogging(scanFiles: string[], context: ITargetContext, taskName: string) {
    Logger.debug(`Start executing ${taskName} and process ${scanFiles.length} files`);

    this.buildProfileUpdater.updateSourceRoots(context); // 更新builde-profile.json5中的sourceRoot

    const processingResult = this.engine.processFilesUnified(scanFiles, context);

    const totalGenerated = processingResult.generatedFiles.length;
    const totalSkipped = processingResult.skippedFiles.length;

    Logger.info(`${taskName} completed: generate ${totalGenerated} files and skip ${totalSkipped} files`);

    if (totalGenerated > 0 && taskName === TaskConstants.SYNC_TASK) {
      const config = context.context.buildProfileOpt;
      const buildProfilePath = SerializationPathUtil.join(context.getModulePath(), 'build-profile.json5');

      SerializationPathUtil.writeFileSync(buildProfilePath, JSON.stringify(config, null, 2));
    }

    this.executeImportRewrite(context, taskName);
    return processingResult;
  }

  protected executeImportRewrite(context: ITargetContext, taskName: string): void {
    const configManager = ConfigManager.getInstance();

    Logger.debug(`Start to execute the import rewrite - ${taskName}`);

    // 收集生成文件信息
    const generatedFileInfos = this.engine.collectGeneratedFileInfos(context);

    if (generatedFileInfos.length === 0) {
      Logger.debug('No file was generated. Skip the import and rewrite');
      return;
    }

    // 获取导入重写配置
    const importRewriteConfig = configManager.getImportRewriteConfig();

    // 执行导入重写
    const importRewriteService = new ImportRewriteServiceImpl();
    importRewriteService.rewriteImports(
      context,
      generatedFileInfos,
      importRewriteConfig
    );

    Logger.info(`Import and rewrite completed - ${taskName}`);
  }

  abstract run(context: ITargetContext): void | Promise<void>;

}